package com.hellomaker.redismq.starter.impl;

import com.hellomaker.redismq.core.mq.SimpleRedisMQClient;
import com.hellomaker.redismq.starter.AutoConfigure;
import com.hellomaker.redismq.starter.RedisMQProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author xianzhikun
 * @version 1.0.1
 */
@Deprecated
public class ClientAutoConfigure implements AutoConfigure {

    Logger logger = LoggerFactory.getLogger(ClientAutoConfigure.class);

    private boolean isConfig(String prop) {
        if (prop != null && !prop.equals("") && !prop.equals("null")) {
            return true;
        }
        return false;
    }

    @Override
    public void configure(ApplicationContext applicationContext) {
        try {
            RedisMQProperties properties = applicationContext.getBean(RedisMQProperties.class);
            SimpleRedisMQClient simpleRedisMQClient = null;
            if (isConfig(properties.getHost()) && properties.getPort() != null) {
                if (properties.getDatabase() == null) {
                    properties.setDatabase(0);
                }
                if (!isConfig(properties.getPassword())) {
                    properties.setPassword("");
                }
                try {
                    logger.info(">>>>>>> redismq client start ");
                    simpleRedisMQClient = new SimpleRedisMQClient(properties.getHost(), properties.getPort(), properties.getDatabase(), properties.getPassword());
                    logger.info(">>>>>>> redismq client start ok >> ip={}, port={}.", properties.getHost(), properties.getPort());
//                    applicationContext.getAutowireCapableBeanFactory().registerSingleton("simpleRedisMQClient", simpleRedisMQClient);

                } catch (Exception e) {
                    logger.error(">>>>>>> redismq client start failed.", e);
                }
            } else {
                logger.warn(">>>>>>> redismq client ignore.");
            }
        } catch(NoSuchBeanDefinitionException e){
            logger.warn(">>>>>>> redismq has not config");
        } catch(Exception e){
            logger.warn(">>>>>>> redismq has exception: ", e);
        }
    }
}
